package com.yh.controller;


import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
public class ShiroController {


    @RequestMapping("/add")
    public String add() {
        return "succ";
    }

    @RequestMapping("/del")
    public String del() {
        return "succ";
    }

    @RequestMapping("/sel")
    public String sel() {
        return "succ";
    }

    @RequestMapping("/upd")
    public String upd() {
        return "succ";
    }


    @RequestMapping("/login")
    public ModelAndView login(String username, String userpwd, Model model) {

        //获取subject
        Subject subject = SecurityUtils.getSubject();

        //封装用户数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, userpwd);

        //执行登录方法

        try {

            subject.login(token);
            System.out.println("======================");
            //登录成功 跳转页面
            return new ModelAndView("redirect:caozuo.html");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            model.addAttribute("msg", "用户名不存在");
            return new ModelAndView("login");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            model.addAttribute("msg", "密码不正确");
            return new ModelAndView("login");
        }
    }
}
